package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.ToDoMapper;
import com.itheima.pojo.Todo;
import com.itheima.service.ToDoService;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author hrz
 * @version 1.0
 * @date 2020-08-03 21:26
 */
@Service
public class ToDoServiceImpl implements ToDoService {
    @Resource
    private ToDoMapper toDoMapper;

    // 生成满足要求的32位uid的私有方法
    private String getNewUID() {
        return UUID.randomUUID().toString().toLowerCase().replaceAll("-", "");
    }

    // 增加待办事项的方法
    @Override
    public String add(Todo todo) {

        String uuid = getNewUID();
        todo.setUid(uuid);
        int insert = toDoMapper.insert(todo);
        if (insert == 0) {
            return "failed";
        }
        return "succeed";
    }

    // 删除待办事项的方法(改变状态)
    @Override
    public String delete(Todo todo) {
        // 设置状态为已删除
        // 默认为1,默认未删除,故0/false为已删除
        todo.setStatus(false);
        todo.setDone(true);
        int update = toDoMapper.updateByPrimaryKeySelective(todo);
        if (update == 0) {
            return "failed";
        }
        return "succeed";
    }
    
    // 编辑待办事项的方法
    @Override
    public String eidt(Todo todo) {
        int update = toDoMapper.updateByPrimaryKeySelective(todo);
        if (update == 0) {
            return "failed";
        }
        return "succeed";
    }
    
    // 获取待办事项列表
    //------------------------------------------------------------
    @Override
    public Page<Todo> getPageList(Map<String, Object> searchMap) {
        Example example = new Example(Todo.class);
        Example.Criteria criteria = example.createCriteria();
        Integer currentPage = (Integer) searchMap.get("currentPage");
        if (currentPage == null) {
            currentPage = 1;
        }
        Integer pageSize = (Integer) searchMap.get("pageSize");
        if (pageSize == null) {
            pageSize = 10;
        }
        // 设置状态为未完成
        criteria.andEqualTo("done",0);
        // 设置状态为未删除
        criteria.andEqualTo("status",1);
        PageHelper.startPage(currentPage, pageSize);
        Page<Todo> pageList = (Page<Todo>) toDoMapper.selectByExample(example);
        return pageList;
    }
}
